package top.dark.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import top.dark.common.utils.HttpUtils;
import top.dark.common.utils.R;
import top.dark.feign.MemberFeignService;
import top.dark.vo.MemberVo;
import top.dark.vo.SocialGithubUserVo;

import javax.servlet.http.HttpServletRequest;
import javax.swing.text.html.parser.Entity;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Author: lijiao
 * description:
 * Create Time: 2021/3/21 22:03
 */
@Slf4j
@Controller
@RequestMapping("/oauth2.0")
public class OAuth2Controller {

    @Autowired
    private MemberFeignService memberFeignService;

    @RequestMapping("/github/success")
    public String oauthGithubLogin(@RequestParam("code") String code, HttpServletRequest request) {
        // 1、根据授权码获取access_token
        String accessToken = "";
        try {
            Map<String, String> querys = new HashMap<>();
            String client_id = "487d861e06a1c9dcc91e";
            String client_secret = "21bedbe07da8284e5d35ccff7e2ffa918cb3b839";
            querys.put("client_id", client_id);
            querys.put("client_secret",client_secret );
            querys.put("code", code);
            HttpResponse resp = HttpUtils.doPost("https://github.com", "/login/oauth/access_token",
                    "post", new HashMap<>(), querys, "");
            if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                // 获取成功
                String respStr = EntityUtils.toString(resp.getEntity());
                if (StringUtils.isNotEmpty(respStr)) {
                    Pattern p = Pattern.compile("=(\\w+)&");
                    Matcher m = p.matcher(respStr);
                    while (m.find()) {
                        accessToken = m.group(1);
                        log.info("令牌token：{}", m.group(1));
                        break;
                    }
                }
            }
        } catch (Exception e) {
            log.error("获取access_token产生异常，异常信息:{}", e);
        }

        // 2、根据access_token获取github的用户信息
        if (StringUtils.isNotEmpty(accessToken)) {
            try {
                Map<String, String> header = new HashMap<>();
                header.put("Authorization", "token " + accessToken);
                HttpResponse resp = HttpUtils.doGet("https://api.github.com", "/user",
                        "get", header, new HashMap<>());
                if (resp != null && resp.getStatusLine().getStatusCode() == 200) {
                    String respStr = EntityUtils.toString(resp.getEntity());
                    SocialGithubUserVo socialVo = JSON.parseObject(respStr, SocialGithubUserVo.class);
                    socialVo.setAccessToken(accessToken);
                    // 当前用户如果是第一次进入网站，自动注册进来（为当前社交用户生成一个会员信息账号，以后社交账号对应指定的会员）
                    R r = memberFeignService.oauthGithubLogin(socialVo);
                    if (r != null && r.getCode() == 0) {
                        // 登录（注册并登录）成功
                        //redirect.addFlashAttribute("loginUser",r.getData(new TypeReference<MemberVo>() {}));
                        request.getSession().setAttribute("loginUser", r.getData(new TypeReference<MemberVo>() {
                        }));
                        return "redirect:http://gulimall.com/";
                    }
                }
            } catch (Exception e) {
                log.error("获取用户社交信息异常，异常信息：{}", e);
            }
        }
        return "redirect:http://auth.gulimall.com/login.html";
    }
}
